package com.atguigu.flink.chapter10;


import com.atguigu.flink.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/9/8 9:02
 */
public class Flink06_High_Project_Order {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        KeyedStream<OrderEvent, Long> stream = env
            .readTextFile("input/OrderLog.csv")
            .map(new MapFunction<String, OrderEvent>() {
                @Override
                public OrderEvent map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new OrderEvent(
                        Long.valueOf(data[0]),
                        data[1],
                        data[2],
                        Long.parseLong(data[3]) * 1000  // 把s变成ms
                    );
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((event, ts) -> event.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId);
        
        // create+pay 或 pay
        Pattern<OrderEvent, OrderEvent> pattern = Pattern
            .<OrderEvent>begin("create", AfterMatchSkipStrategy.skipPastLastEvent())
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "create".equals(value.getEventType());
                }
            }).optional()
            .next("pay")
            .where(new SimpleCondition<OrderEvent>() {
                @Override
                public boolean filter(OrderEvent value) throws Exception {
                    return "pay".equals(value.getEventType());
                }
            })
            .within(Time.minutes(30));
        
        // 1. 超时: create
        PatternStream<OrderEvent> ps = CEP.pattern(stream, pattern);
        SingleOutputStreamOperator<OrderEvent> normal = ps.flatSelect(
            new OutputTag<OrderEvent>("timeout") {},
            new PatternFlatTimeoutFunction<OrderEvent, OrderEvent>() {
                @Override
                public void timeout(Map<String, List<OrderEvent>> map,
                                    long timeoutTimestamp,
                                    Collector<OrderEvent> out) throws Exception {
                    // map中只有一个 key : create
                    OrderEvent create = map.get("create").get(0);
                    
                    out.collect(create);
                    
                }
            },
            new PatternFlatSelectFunction<OrderEvent, OrderEvent>() {
                @Override
                public void flatSelect(Map<String, List<OrderEvent>> map,
                                       Collector<OrderEvent> out) throws Exception {
                    // 匹配成功的: 一种是 create+pay  一种只有 pay
                    if (!map.containsKey("create")) {
                        // 没有 creare
                        out.collect(map.get("pay").get(0));
                        
                    }
                    
                }
            }
        );
        
       /* normal
            .getSideOutput(new OutputTag<OrderEvent>("timeout") {})
            .map(new MapFunction<OrderEvent, String>() {
                @Override
                public String map(OrderEvent value) throws Exception {
                    return "订单: " + value.getOrderId() + " 只有 create 或者 超时支付";
                }
            }).print();
        normal
            .map(new MapFunction<OrderEvent, String>() {
                @Override
                public String map(OrderEvent value) throws Exception {
                    return "订单: " + value.getOrderId() + " 只有 pay";
                }
            })
            .print("正常");*/
        normal
            .getSideOutput(new OutputTag<OrderEvent>("timeout") {}).union(normal)
            .keyBy(OrderEvent::getOrderId)
            .process(new KeyedProcessFunction<Long, OrderEvent, String>() {
    
                private ValueState<OrderEvent> createState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void processElement(OrderEvent value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 如果 create 来了, 把 create 放入到状态中
                    // 如果来了 pay, 判断状态中是否有 create, 如果有就是超时
                    // 如果没有 create, 就是只有 pay
                    if ("create".equals(value.getEventType())) {
                        createState.update(value);
                        
                    }else{
                        if (createState.value() != null) {
                            // pay 来的时候, create 已经到了
                            out.collect("订单: " + value.getOrderId() + "超时支付");
                        }else{
                            out.collect("订单: " + value.getOrderId() + "只有pay");
                            
                        }
                    }
                    
                }
            })
            
            .print();
        
        env.execute();
    }
}
/*
异常:
    1. 超时支付
    2. 只有支付没有创建
    
 */